﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tanmia.Core;
using Tanmia.Basis.Domain;

namespace Tanmia.Domain
{
    public class PaymentDomain : BaseDomainObject<Payment>
    {
        private VoucherDomain voucherObj = new VoucherDomain();
        private AccountDomain accountObj = new AccountDomain();

        public void Post(Payment payment)
        {
            if (payment.PaymentID == 0)
                throw new InvalidOperationException("لا يمكن ترحيل دفعة لم تحفظ بعد");

            if (voucherObj.SaveOrUpdate(ConvertToVoucer(payment)).VoucherID == 0)
                throw new Exception("حدث خطأ أثناء إنشاء القيد المالي");
        }

        public void Unpost(Payment payment)
        {

        }

        private Voucher ConvertToVoucer(Payment payment)
        {
            Voucher reVal = new Voucher();

            reVal.CreateDate = payment.CreateDate;
            reVal.PaymentID = payment.PaymentID;
            reVal.User = payment.User;

            if (payment.PaymentType == PaymentTypeEnum.FromCustomer)
            {
                reVal.Notes = "دفعة على حساب الزبون";
                reVal.Details.Add(new VoucherDetail() { Account = accountObj.GetByNumber(Account.FundAccount), Debit = payment.Value, Notes = string.Format("دفعة على حساب الزبون: {0}, رقم {1}", payment.Person.Name, payment.PaymentID) });
                reVal.Details.Add(new VoucherDetail() { Account = payment.Person.Account, Credit = payment.Value, Notes = string.Format("دفعة على حساب الزبون رقم {0}", payment.PaymentID) });
            }
            else
            {
                reVal.Notes = "دفعة على حساب التاجر";
                reVal.Details.Add(new VoucherDetail() { Account = payment.Person.Account, Debit = payment.Value, Notes = string.Format("دفعة على حساب المورد رقم {0}", payment.PaymentID) });
                reVal.Details.Add(new VoucherDetail() { Account = accountObj.GetByNumber(Account.FundAccount), Credit = payment.Value, Notes = string.Format("دفعة على حساب المورد: {0}, رقم {1}", payment.Person.Name, payment.PaymentID) });
            }

            return reVal;
        }
    }
}
